package info.javatech.jmf.client.wrappers;

import info.javatech.jmf.client.controller.JMFAbstractComponentWrapper;
import info.javatech.jmf.client.controller.exceptions.ComponentConstructionException;
import info.javatech.jmf.client.controller.wsclient.PCommand;
import info.javatech.jmf.client.controller.wsclient.PComponent;
import info.javatech.jmf.client.controller.wsclient.PEvent;
import info.javatech.jmf.client.controller.wsclient.PItem;
import info.javatech.jmf.client.controller.wsclient.PScreenContainer;
import info.javatech.jmf.client.util.InvalidComponentException;
import info.javatech.jmf.client.util.PComponentUtils;
import info.javatech.jmf.common.ProtocolConstants;
import info.javatech.jmf.common.components.FormConstants;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;

/**
 *
 * @author afedotov
 */
public class FormWrapper extends JMFAbstractComponentWrapper{
    
    public Object constructInstanceImplementation(PComponent pc) throws ComponentConstructionException {
        Form form;
        try {
            form = new Form(PComponentUtils.getStringProperty(pc, FormConstants.TITLE_PROPERTY_NAME));
            
            form.setCommandListener(getController());
            
            PCommand[] commands = ((PScreenContainer)pc).getCommands();
            PItem[] items = ((PScreenContainer)pc).getItems();
            
            for(int i = 0;i<commands.length;i++) {
                Command command = (Command) getController().askToConstruct(commands[i]);
                form.addCommand(command);
            }
            
            for(int i = 0;i<items.length;i++)
            {
                Item item = (Item) getController().askToConstruct(items[i]);
                form.append(item);
            }
            
            return form;
        } catch (InvalidComponentException ex) {
            throw new ComponentConstructionException();
        }
        
    }
    
    public PComponent persistImplementation(Object obj, PComponent eventSource) {
        Form form = (Form) obj;
        
        PComponent res = new PScreenContainer();
        res.setPropertyNames(new String[]{});
        res.setPropertyValues(new String[]{});
        
        res.setType(FormConstants.TYPE_NAME);
        
        return res;
    }
    
    public PEvent handleEvent(Displayable displayable, Item Item, Command command) {
        return new PEvent(getController().askToPersist(command),ProtocolConstants.EVENT_KIND_COMMAND);
    }
}
